//
//  MYStatusPictureView.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/18.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

//字典转模型时没有return
/*
2016-04-18 15:09:47.115 MYWeibo[24691:817281] the behavior of the UICollectionViewFlowLayout is not defined because:
2016-04-18 15:09:47.115 MYWeibo[24691:817281] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2016-04-18 15:09:47.116 MYWeibo[24691:817281] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fa0d313ce50>, and it is attached to <MYWeibo.MYStatusPictureView: 0x7fa0d185c800; baseClass = UICollectionView; frame = (8 90; 100 150); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fa0d0ef92d0>; layer = <CALayer: 0x7fa0d0ef9f90>; contentOffset: {0, 0}; contentSize: {0, 0}> collection view layout: <UICollectionViewFlowLayout: 0x7fa0d313ce50>.
2016-04-18 15:09:47.116 MYWeibo[24691:817281] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
fatal error: NSArray element failed to match the Swift Array Element type
*/

import UIKit
import SDWebImage

//图片之间的间距
private let cellId = "cellId"
let PictureCellMargin: CGFloat = 3
//获取固定值
//配图视图的最大宽度
private let picViewWidth = ScreenWidth - 2 * StatusCellMargin
//图片的尺寸
private let itemWidth = (picViewWidth - 2 * PictureCellMargin) / 3

class MYStatusPictureView: UICollectionView {

    var imageURLs: [MYStatusPicture]? {
        didSet {
            //根据模型数组的数量 计算配图视图的大小
            //print(imageURLs?.count)
            
            let picSize = calculatePicViewSize()
            //更新约束 update  不是make
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(picSize)
                
                //更新textLabel
                textLabel.text = "\(imageURLs?.count ?? 0)"
                //刷新数据
                reloadData()
            }
            
        }
    }
    
    //计算配图视图的大小
    private func calculatePicViewSize() ->CGSize {
    
        let imageCount = imageURLs?.count ?? 0
        
        //将layout的itemsize设置的和图片一样大
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if imageCount == 0 {
            return CGSizeZero
        }
        
        if imageCount == 1 {
            //TODO: 后期完善
            let imgViewSize = CGSize(width: 100, height: 150)
            layout.itemSize = imgViewSize
            return imgViewSize
        }
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        //其他情况
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let h = itemWidth * row + PictureCellMargin * (row - 1)
        return CGSize(width: picViewWidth, height: h)
        
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        //layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        self.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        self.setupUI()
        //注册cell
        self.registerClass(PictureCell.self, forCellWithReuseIdentifier: cellId)
        //设置数据源
        self.dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
    
        addSubview(textLabel)
        textLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        scrollsToTop = false
    }
    
private lazy var textLabel: UILabel = UILabel(text: "", textColor: UIColor.orangeColor(), fontSize: 30, margin: PictureCellMargin)

}



extension MYStatusPictureView: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        //注册cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! PictureCell
        //测试颜色
        //cell.backgroundColor = randomColor()
        cell.statusPic = imageURLs![indexPath.item]
        
        return cell
    }
    
}


class PictureCell: UICollectionViewCell {
    
    var statusPic: MYStatusPicture? {
    
        didSet {
        
            //给图片赋值
            let url = NSURL(string: statusPic?.thumbnail_pic ?? "")
            picView.sd_setImageWithURL(url)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI界面
    private func setupUI() {
        
        contentView.addSubview(picView)
        //设置约束
        picView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //MARK: 懒加载子视图
    private lazy var picView: UIImageView = {
    
        let p = UIImageView()
        //设置图片填充模式
        p.contentMode = .ScaleAspectFill
        //手写代码需要手动裁剪
        p.clipsToBounds = true
        return p
        
    }()

}






